/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.onlylemi.mapview.menu;

import com.onlylemi.mapview.ResourceTable;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.List;

/**
 * 菜单item适配器
 *
 * @since 2021-06-03
 */
public class MenuProvider extends BaseItemProvider {

    private Context context;

    // ListContainer的数据集合
    private List<String> dataList;

    /**
     * 构造函数
     *
     * @param context
     * @param list
     */
    public MenuProvider(Context context, List<String> list) {
        this.context = context;
        this.dataList = list;
    }

    @Override
    public int getCount() {
        return dataList == null ? 0 : dataList.size();
    }

    @Override
    public Object getItem(int position) {
        if (dataList != null && position >= 0 && position < dataList.size()) {
            return dataList.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        String data = dataList.get(position);
        final Component cpt;
        ViewHolder holder;
        if (component == null) {
            cpt = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_menu, null, false);
            holder = new ViewHolder(cpt);

            // 将获取到的子组件信息绑定到列表项的实例中
            cpt.setTag(holder);
        } else {
            cpt = component;

            // 从缓存中获取到列表项实例后，直接使用绑定的子组件信息进行数据填充。
            holder = (ViewHolder) cpt.getTag();
        }
        holder.tvName.setText(data);
        return cpt;
    }

    /**
     * ViewHolder
     *
     * @since 2021-06-03
     */
    static class ViewHolder {
        Text tvName;

        ViewHolder(Component component) {
            tvName = (Text) component.findComponentById(ResourceTable.Id_tv_name);
        }
    }
}